#include "dut/Mesh.h"

using namespace Dut;

HRESULT Dut::MeshIndice::Create(ID3D11Device* device,const Desc& desc)
{

    D3D11_BUFFER_DESC vbd;
    ZeroMemory(&vbd, sizeof(vbd));
    vbd.Usage = D3D11_USAGE_IMMUTABLE;
    vbd.ByteWidth = desc.vertexSize;
    vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vbd.CPUAccessFlags = 0;

    D3D11_SUBRESOURCE_DATA InitData;
    ZeroMemory(&InitData, sizeof(InitData));
    InitData.pSysMem = desc.vertices;

    HR(device->CreateBuffer(&vbd, &InitData, m_pVertexBuffer.GetAddressOf()));
 
    D3D11_BUFFER_DESC ibd;
    ZeroMemory(&ibd, sizeof(ibd));
    ibd.Usage = D3D11_USAGE_IMMUTABLE;
    ibd.ByteWidth = desc.indiceSize;
    ibd.BindFlags = D3D11_BIND_INDEX_BUFFER;
    ibd.CPUAccessFlags = 0;
    InitData.pSysMem = desc.indices;
 
   HR(device->CreateBuffer(&ibd, &InitData, m_pIndexBuffer.GetAddressOf()));

    m_IndiceType = GetIndiceType(desc.indiceStride);
    m_VertexStride = desc.vertexStride;
    m_NumIndices = desc.numIndices;

    return true;

}

DXGI_FORMAT Dut::MeshIndice::GetIndiceType(const int& sz)
{
    if (sz == 4) {
        return DXGI_FORMAT_R32_UINT;
    }
    else if (sz == 2)
    {
        return DXGI_FORMAT_R16_UINT;
    }
    else
    {
        return DXGI_FORMAT_R8_UINT;
    }
}

void Dut::MeshIndice::DrawIndexed(ID3D11DeviceContext* context)
{

    context->IASetIndexBuffer(m_pIndexBuffer.Get(), m_IndiceType, 0);

    UINT offset = 0;
    context->IASetVertexBuffers(0, 1, m_pVertexBuffer.GetAddressOf(), &m_VertexStride, &offset);
    context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    context->DrawIndexed(m_NumIndices, 0, 0);

}